// TCP Client
// 
// A client application written to connect to a TCP echo server.
// 
// Author: F.M.A. Erich
// HAN University of Applied Science
// Arnhem, The Netherlands

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Mono.Unix.Native;

namespace TCPClient
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			if (args.Length != 1)
			{
				Console.WriteLine("Missing parameter: Destination Port");
				Environment.Exit(1);
			}
			String server = "127.0.0.1"; // localhost
			int port = Convert.ToInt32(args[0]);
			
			string[] splitted = server.Split('.');
			byte[] splittedBytes = new byte[4];
			for(int i=0;i<4;i++)
			{
				splittedBytes[i] = (Convert.ToByte(splitted[i]));
			}
			
			Console.WriteLine("{0}.{1}.{2}.{3}", (int) splittedBytes[0], (int) splittedBytes[1], (int) splittedBytes[2], (int) splittedBytes[3]);
			TcpClient client = new TcpClient();
			IPAddress ipa = new IPAddress(splittedBytes);
			client.Connect(ipa, 9050);
			NetworkStream ns = client.GetStream();
			
			while(true)
			{
				String readBuffer = Console.ReadLine();
				byte[] writeBuffer = new byte[readBuffer.Length];
				byte[] packet = Encoding.ASCII.GetBytes(readBuffer);
				
				try {
					ns.Write(packet, 0, packet.Length);
				} catch (SocketException se) {
					Syscall.perror("socket");
					Environment.Exit(1);
				}
				
				try {
					ns.Read(writeBuffer, 0, packet.Length);
				} catch (SocketException se) {
					Syscall.perror("socket");
					Environment.Exit(1);
				}
				
				Console.WriteLine("{0}", System.Text.ASCIIEncoding.ASCII.GetString(writeBuffer));
			}
		}
	}
}